package com.zhaokuner.pm.filter;

import org.apache.logging.log4j.ThreadContext;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <p>Description: 日志拦截器</p>
 * <p>
 *
 * @author zhaoxikun
 * @date 2020/7/26 17:05
 */
@WebFilter
@Component
public class LogWebFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ThreadContext.put("logId", LocalDateTime.now().format(dateTimeFormatter) + "" + ThreadLocalRandom.current().nextInt(10000, 100000));
        filterChain.doFilter(servletRequest, servletResponse);
        ThreadContext.clearAll();
    }

    @Override
    public void destroy() {

    }
}
